
<template>
  <div class='subject-dialog'>
      <el-dialog width="400px" :visible.sync="showDialog" :title="`${data.id?'修改学科':'新增学科'}`" @close="showDialog = false">
        <!-- 表单内容 -->
        <el-form ref="form" :model="formData" :rules="rules" label-width="80px">
          <el-form-item label="学科名称" prop="subjectName">
            <el-input v-model="formData.subjectName" placeholder="请输入学科名称" />
          </el-form-item>
          <el-form-item label="是否显示" prop="isFrontDisplay">
            <el-switch
            v-model="formData.isFrontDisplay"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </el-form-item>
        </el-form>
        <template slot="footer">
          <div>
            <el-button @click="showDialog = false">取消</el-button>
            <el-button @click="confirm()" type="primary">确认</el-button>
          </div>
        </template>
      </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/subjects.js'
export default {
  name: 'subjectsAdd',
  props: {
    data: {
      default: () => {},
      type: Object
    }
  },
  data () {
    return {
      showDialog: false,
      formData: {
        id: null,
        subjectName: null,
        isFrontDisplay: 1
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', tirgger: 'blur' }
        ],
        isFrontDisplay: [
          { type: 'number', message: '请选择是否显示', tirgger: 'blur' }
        ]
      }
    }
  },
  methods: {
    open () {
      this.showDialog = true
      if (this.data.id) {
        const { id, subjectName, isFrontDisplay } = this.data
        this.formData = { id, subjectName, isFrontDisplay }
      } else {
        this.formData = {
          id: null,
          subjectName: null,
          isFrontDisplay: 1
        }
      }
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    async confirm () {
      this.$refs.form.validate(async boo => {
        if (!boo) return

        if (!this.data.id) {
          // 新增
          await add(this.formData)
        } else {
          // 修改
          this.formData.id = this.data.id
          await update(this.formData)
        }
        this.$message.success(this.data.id ? '编辑学科成功' : '新增学科成功')
        this.showDialog = false
        this.$emit('handleSubmit')
      })
    }
  }
}
</script>

<style scoped lang='scss'></style>
